<?php

namespace common\model;

use think\model\RelationModel;
use think\module\Module;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\SplSubjectEnforcer;

class ReviewFeedbackEntityModel extends RelationModel implements SplSubject
{
    use SplSubjectEnforcer;

    const ENABLE_DEFAULT = 'default';
    const ENABLE_YES = 'yes';
    const ENABLE_NO = 'no';


    const PUBLISHED_YES = 'yes';
    const PUBLISHED_NO = 'no';
    // 自动验证
    protected $_validate = [


        ['review_feedback_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_module_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['is_append', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'], // 是否新增
        ['enable', ['default', 'yes', 'no'], '', self::EXISTS_VALIDATE, 'in'], // 是否启用
        ['published', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'], // 是否发布


        ['json', '', '', self::EXISTS_VALIDATE, 'array']
    ];

    // 自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],

        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['updated_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['updated', 'time', self::MODEL_UPDATE, 'function'],

    ];


    // 隐藏字段
    protected $hidden = ['json'];

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getJsonAttr($value, $data)
    {
        // 当前模块的自定义字段配置
        $currentModuleCode = empty(\request()->getModuleCode()) ? 'entity' : \request()->getModuleCode();
        $fieldDict = Module::$moduleDictData['field_index_by_code'][$currentModuleCode]['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $filed => $config) {
            if (array_key_exists($filed, $jsonDictData)) {
                $this->appendCustomField[$filed] = $jsonDictData[$filed];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$filed] = "";
            }
        }

        return $jsonDictData;
    }

}
